package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.constant.Sysconst;
import cn.chinaflame.pagodas.dto.AreaDto;
import cn.chinaflame.pagodas.entity.YwArea;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.repository.YwAreaRepository;
import cn.chinaflame.pagodas.utils.DateTimes;
import cn.chinaflame.pagodas.utils.ParamPreconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Map;

/**
 * 区域service
 *
 * @author created by boming
 * @date 2018年1月6日 下午2:35:17
 */
@Service
public class YwAreaService {


    private static final Logger log = LoggerFactory.getLogger(YwAreaService.class);

    @Autowired
    private YwAreaRepository ywAreaRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询区域列表
     *
     * @param code       区域编码
     * @param parentCode 父区域编码
     * @param type       区域类型
     * @return
     */
    public List<AreaDto> queryList(String code, String parentCode, String type) {
        log.info("查询区域列表code:{},parentCode:{},type:{}", code, parentCode, type);
        List<YwArea> positionList = ywAreaRepository.findAll(new Specification<YwArea>() {
            @Override
            public Predicate toPredicate(Root<YwArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = Lists.newArrayList();
                if (!Strings.isNullOrEmpty(code))
                    list.add(cb.equal(root.get("code").as(String.class), code));
                if (!Strings.isNullOrEmpty(parentCode))
                    list.add(cb.like(root.get("parentCode").as(String.class), parentCode));
                if (!Strings.isNullOrEmpty(type))
                    list.add(cb.equal(root.get("type").as(String.class), type));
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        });
        List<AreaDto> dtoList = Lists.newArrayList();
        for (YwArea position : positionList) {
            AreaDto dto = new AreaDto();
            BeanUtils.copyProperties(position, dto);
            dtoList.add(dto);
        }
        return dtoList;
    }

    /**
     * 查询代理全部区域和项目
     *
     * @param Agentid
     * @return
     */
    public String queryByAgents(String agentid) {
        log.info("根据代理查询区域agentid:{}", agentid);
        String sql = "select result  from vw_agents where id = '" + agentid + "'";
        String idStr = jdbcTemplate.queryForObject(sql, java.lang.String.class);
        return idStr;
    }

    public Object queryLeftList() {

        String sql = "select *  from vw_province_city ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

        return list;
    }

    /**
     * 添加区域
     *
     * @param code
     * @param name
     * @param parentCode
     * @param type
     * @return
     */
    public AreaDto add(String code, String name, String parentCode, String type) {
        log.info("添加区域code:{},name:{},parentCode:{},type", code, name, parentCode, type);
        YwArea oldEntity = ywAreaRepository.findOne(code);
        ParamPreconditions.checkArgument(oldEntity != null, CodeEnum.FAIL.getCode(), "记录已经存在");
        if (!Sysconst.AREA_TYPE_PROVINCE.equals(type)) {
            YwArea parentEntity = ywAreaRepository.findOne(parentCode);
            ParamPreconditions.checkNotNull(parentEntity, CodeEnum.FAIL.getCode(), "未找到父区域");
        }
        YwArea entity = new YwArea();
        entity.setCode(code);
        entity.setParentCode(Sysconst.AREA_TYPE_PROVINCE.equals(type) ? null : parentCode);
        entity.setName(name);
        entity.setType(type);
        entity.setCreatetime(DateTimes.nowDateTime());
        entity.setUpdatetime(DateTimes.nowDateTime());
        entity = ywAreaRepository.saveAndFlush(entity);
        AreaDto dto = new AreaDto();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    /**
     * 更新区域
     *
     * @param code
     * @param name
     * @param parentCode
     * @param type
     * @return
     */
    public AreaDto update(String code, String name, String parentCode, String type) {
        log.info("更新区域code:{},name:{},parentCode:{},type", code, name, parentCode, type);
        YwArea entity = ywAreaRepository.findOne(code);
        ParamPreconditions.checkArgument(entity != null, CodeEnum.FAIL.getCode(), "未找到记录");
        if (!Sysconst.AREA_TYPE_PROVINCE.equals(type)) {
            YwArea parentEntity = ywAreaRepository.findOne(parentCode);
            ParamPreconditions.checkNotNull(parentEntity, CodeEnum.FAIL.getCode(), "未找到父区域");
        }
        entity.setParentCode(Sysconst.AREA_TYPE_PROVINCE.equals(type) ? null : parentCode);
        entity.setName(name);
        entity.setType(type);
        entity.setUpdatetime(DateTimes.nowDateTime());
        entity = ywAreaRepository.saveAndFlush(entity);
        AreaDto dto = new AreaDto();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    /**
     * 删除区域
     *
     * @param id
     * @return
     */
    public Boolean delete(String code) {
        log.info("删除区域code:{}", code);
        ywAreaRepository.delete(code);
        return true;
    }
}
